<?php
class BaseDb{

	public $handle;
	private $_dsn;
	private $username;
	private $passwod;
	private $resource;
	private $_ret;
	private $column;
	

	public function __construct($config){
		$this->_dsn = "mysql:host={$config['mysql']['host']};dbname={$config['mysql']['database']};charset=utf8";
		$this->username = $config['mysql']['username'];
		$this->password = $config['mysql']['password'];
		$this->connect();

	}

	private function connect(){
		try{
			$this->handle = new PDO($this->_dsn, $this->username, $this->password);
			$this->handle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		}catch(PDOException $e){
			echo $e->getMessage();
			exit;
		}
	}

	/**
	 * multi_insert = 1 一次性插入多行
	 *
	 */
	public function query($sql, $params=null, $multi_insert=0){
		try{
			if( $multi_insert ){
				$this->handle->beginTransaction();
				$this->resource = $this->handle->prepare($sql);
				$this->resource->execute( $params );
				$this->_ret = $this->handle->commit();
			}else{
				$this->resource = $this->handle->prepare($sql);
				if( is_array($params) && !empty($params) ){
					$this->_ret = $this->resource->execute( array_values($params) );
				}else{
					$this->_ret = $this->resource->execute();
				}
			}
		}catch(PDOException $e){
			echo $e->getMessage();
			exit;
		}

	}

	public function fetch(){
		return $this->resource->fetch(PDO::FETCH_ASSOC);
	}

	public function fetchAll(){
		return $this->resource->fetchAll(PDO::FETCH_ASSOC);
	}
	
	public function insert(){
		return $this->_ret;
	}

	public function lastInsertId(){
		return $this->handle->lastInsertId();
	}

}
